package huanzhao.erp.other.aspect;

import huanzhao.erp.domain.annotation.CheckPosition;
import huanzhao.erp.domain.entity.GlobalSetting;
import huanzhao.erp.domain.entity.Staff;
import huanzhao.erp.domain.po.Result;
import huanzhao.erp.domain.types.DeptPositionType;
import huanzhao.erp.service.BasicService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


@Aspect
@Component
public class CheckPositionAspect {
    private final BasicService basicService;

    public CheckPositionAspect(BasicService basicService) {
        this.basicService = basicService;
    }

    /**
     * 定义切点
     */
    @Pointcut("@annotation(huanzhao.erp.domain.annotation.CheckPosition)")
    public void pointCut() {
    }

    /**
     * 环绕通知
     */
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取被注解的方法
        MethodInvocationProceedingJoinPoint mjp = (MethodInvocationProceedingJoinPoint) joinPoint;
        MethodSignature signature = (MethodSignature) mjp.getSignature();
        Method method = signature.getMethod();
        // 获取方法上的注解
        CheckPosition checkPosition = method.getAnnotation(CheckPosition.class);
        DeptPositionType[] positionTypes = checkPosition.value();
        // 若指定的要校验的职位类型为空，则直接放行
        if (positionTypes == null) {
            return joinPoint.proceed();
        }

        Staff currentStaff = basicService.getCurrentStaff();
        GlobalSetting globalSetting = basicService.getGlobalSetting();
        // 若当前员工是业务经理，则直接放行
        Long staffId = currentStaff.getId();
        if (staffId.equals(globalSetting.getManagerId())) {
            return joinPoint.proceed();
        }
        for (DeptPositionType positionType : positionTypes) {
            // 检查员工是否符合要求
            boolean fit = switch (positionType) {
                case FINANCER -> staffId.equals(globalSetting.getFinancerId());
                case REPAIR_LEADER -> staffId.equals(globalSetting.getRepairLeaderId());
                case PURCHASE_HANDLER -> staffId.equals(globalSetting.getPurchaseHandlerId());
                case WAREHOUSE_HANDLER -> staffId.equals(globalSetting.getWarehouseHandlerId());
                case REPAIR -> currentStaff.getMaintainer();
                case PURCHASER -> currentStaff.getPurchaser();
                case WAREHOUSER -> currentStaff.getWarehouser();
                default -> false;
            };
            if (fit) {
                // 符合要求则放行
                return joinPoint.proceed();
            }
        }
        return Result.error("身份校验未通过，您没有权限执行此操作");
    }
}
